package club.banyuan.hrms.servlet;

import club.banyuan.hrms.dao.AdminDao;
import club.banyuan.hrms.dao.impl.AdminDaoImpl;
import club.banyuan.hrms.dao.impl.AdminDbDaoImpl;
import club.banyuan.hrms.domain.Admin;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    private AdminDao adminDao;

    @Override
    public void init() throws ServletException {
        adminDao = new AdminDbDaoImpl();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 根据用户名和密码查询用户
        Admin admin = adminDao.getAdminByUsernameAndPassword(username, password);
        if (admin != null) {
            HttpSession session = request.getSession();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
//            设置session失效时间，单位是秒
//            session.setMaxInactiveInterval(60);
            session.setAttribute("account", admin);
            session.setAttribute("time", date);

            // 跳转到登录后的首页
            response.sendRedirect("home_page.jsp");
        } else {
            // 无权登录时跳转到登录页面
            response.sendRedirect("login.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
